<!-- 注册 -->
<template>
  <SimpleHeaderbar />
  <div id="container" class="flex justify-center">
    <div id="login-form">
      <div class="big-text" v-if="!emailValideted">您在哪里进行研究？</div>
      <div class="small-text" v-if="!emailValideted">
        我们将通过邮箱来判断您的科研机构,并帮助您找到您的同事。
      </div>
      <div class="big-text" v-if="emailValideted">邮箱已通过验证。</div>
      <div class="small-text" v-if="emailValideted">请补充个人信息并注册。</div>
      <n-form ref="formRef" :model="model" :rules="rules">
        <n-form-item path="email" label="邮箱" :label-style="labelStyle">
          <n-input
            v-model:value="model.email"
            @keydown.enter.prevent
            :disabled="emailValideted"
          />
        </n-form-item>
        <n-grid :cols="2" :x-gap="24">
          <n-form-item-gi
            path="password"
            label="密码"
            v-if="emailValideted"
            :label-style="labelStyle"
          >
            <n-input
              v-model:value="model.password"
              type="password"
              @keydown.enter.prevent
            />
          </n-form-item-gi>
          <n-form-item-gi
            ref="rPasswordFormItemRef"
            first
            path="reenteredPassword"
            label="重复密码"
            v-if="emailValideted"
            :label-style="labelStyle"
          >
            <n-input
              v-model:value="model.reenteredPassword"
              :disabled="!model.password"
              type="password"
              @keydown.enter.prevent
            />
          </n-form-item-gi>
        </n-grid>

        <n-grid :cols="2" :x-gap="24">
          <n-form-item-gi
            path="name"
            label="姓名"
            :label-style="labelStyle"
            v-if="emailValideted"
            class="half-size-input"
          >
            <n-input v-model:value="model.name" @keydown.enter.prevent />
          </n-form-item-gi>
          <n-form-item-gi
            path="degree"
            label="学历"
            :label-style="labelStyle"
            v-if="emailValideted"
            class="half-size-input"
          >
            <n-select v-model:value="model.degree" :options="DEGREES_OPTIONS" />
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="2" :x-gap="24">
          <n-form-item-gi
            path="institution"
            label="机构"
            :label-style="labelStyle"
            v-if="emailValideted"
            class="half-size-input"
          >
            <n-input
              v-model:value="model.institution"
              @keydown.enter.prevent
              :disabled="emailValideted"
            />
          </n-form-item-gi>
          <n-form-item-gi
            path="department"
            label="所属单位(具体)"
            :label-style="labelStyle"
            v-if="emailValideted"
            class="half-size-input"
          >
            <n-input v-model:value="model.department" @keydown.enter.prevent />
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="2" :x-gap="24">
          <n-form-item-gi
            path="position"
            label="职称"
            :label-style="labelStyle"
            v-if="emailValideted"
            class="half-size-input"
          >
            <n-select
              v-model:value="model.position"
              :options="POSITIONS_OPTIONS"
            />
          </n-form-item-gi>
          <n-form-item-gi
            path="field"
            label="研究领域"
            :label-style="labelStyle"
            v-if="emailValideted"
            class="half-size-input"
            placeholder="请选择"
          >
            <n-select v-model:value="model.field" :options="FIELDS_OPTIONS" />
          </n-form-item-gi>
        </n-grid>
        <n-form-item
          path="currentactivity"
          label="个人简介"
          :label-style="labelStyle"
          v-if="emailValideted"
        >
          <n-input
            v-model:value="model.currentactivity"
            @keydown.enter.prevent
          />
        </n-form-item>
        <n-row :gutter="[0, 24]">
          <n-col :span="24">
            <div style="display: flex; justify-content: flex-end">
              <n-button
                v-if="!emailValideted"
                :disabled="
                  !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(
                    model.email
                  )
                "
                round
                type="primary"
                @click="handleValidateEmail"
                :loading="isverifying"
              >
                验证邮箱
              </n-button>
              <n-button
                v-if="emailValideted"
                :disabled="
                  !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(
                    model.email
                  )
                "
                round
                type="primary"
                @click="handleregisterClick"
              >
                注册
              </n-button>
            </div>
          </n-col>
        </n-row>
      </n-form>

      <!-- 弹窗，用来验证邮箱 -->
      <n-modal
        v-model:show="showEmailModal"
        :mask-closable="false"
        preset="dialog"
        :on-after-leave="closeEmailModal"
        class="email-modal"
      >
        <template #header>
          <div>邮箱验证</div>
        </template>
        <div>
          您的邮箱<span class="email-text">{{ model.email }}</span
          >是符合要求的机构邮箱，现在我们给您的邮箱发了验证邮件。
        </div>
        <div>
          请输入验证码:
          <n-input
            v-model:value="model.identifyCode"
            placeholder="验证码"
            size="small"
            :maxlength="6"
            :on-input="codeUpdate"
            :loading="isverifying"
          />
        </div>
      </n-modal>
    </div>
  </div>
</template>

<script setup>
import SimpleHeaderbar from '../../components/common/SimpleHeaderbar.vue'
import api from '@/api/api'
import { DEGREES, POSITIONS, FIELDS } from '@/assets/constant/UserInfo'
const { Entry } = api
const DEGREES_OPTIONS = DEGREES.map((item) => {
  return {
    label: item,
    value: item
  }
})

const POSITIONS_OPTIONS = POSITIONS.map((item) => {
  return {
    label: item,
    value: item
  }
})

const FIELDS_OPTIONS = FIELDS.map((item) => {
  return {
    label: item,
    value: item
  }
})
// const route = useRoute()
const formRef = ref(null)
const rPasswordFormItemRef = ref(null)
const message = useMessage()
const router = useRouter()

//验证邮箱是否为机构邮箱
const handleValidateEmail = function () {
  isverifying.value = true
  //调接口
  const params = {
    email: model.value.email
  }
  console.log('emailparams', params)
  Entry.verifymail(params)
    .then((res) => {
      if (res.success) {
        message.success('验证成功')
        showEmailModal.value = true
        model.value.institution = res.institution
      } else {
        message.error(res.result)
      }
      isverifying.value = false
    })
    .catch((err) => {
      message.error('出现错误', err)
      isverifying.value = false
      console.log('error:', err)
    })
}
//邮箱是否已经验证
const emailValideted = ref(false)
//邮箱验证弹窗
const showEmailModal = ref(false)
//弹窗取消
const closeEmailModal = function () {
  showEmailModal.value = false
}
//验证码验证
const isverifying = ref(false)
const codeUpdate = function (value) {
  if (value.length === 6) {
    isverifying.value = true
    //调接口
    const params = {
      email: model.value.email,
      identifyCode: model.value.identifyCode
    }
    Entry.codeverify(params)
      .then((res) => {
        if (res.success) {
          emailValideted.value = true
          message.success('验证成功')
          showEmailModal.value = false
        } else {
          message.error(res.result)
        }
        isverifying.value = false
      })
      .catch((err) => {
        message.error('出现错误', err)
        console.log('error:', err)
        isverifying.value = false
      })
  }
}

//表单
const model = ref({
  email: '',
  password: '',
  reenteredPassword: '',
  identifyCode: '',
  name: '',
  degree: '',
  currentactivity: '',
  field: '',
  position: '',
  department: '',
  institution: ''
})

function validatePasswordStartWith(rule, value) {
  return (
    !!model.value.password &&
    model.value.password.startsWith(value) &&
    model.value.password.length >= value.length
  )
}
function validatePasswordSame(rule, value) {
  return value === model.value.password
}

const rules = {
  email: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入邮箱')
        } else if (
          !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)
        ) {
          return new Error('请输入正确的邮箱')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  name: [
    {
      required: true,
      message: '请输入姓名'
    }
  ],
  institution: [
    {
      required: true
    }
  ],
  password: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入密码')
        } else if (!/^[\w]{6,20}$/.test(value)) {
          return new Error('密码要求6~20位')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  reenteredPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur']
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input'
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input']
    }
  ]
}

const handleregisterClick = function (e) {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    if (!errors) {
      const params = {
        email: model.value.email,
        password: model.value.password,
        name: model.value.name,
        degree: model.value.degree,
        field: model.value.field,
        department: model.value.department,
        position: model.value.position,
        currentActivity: model.value.currentactivity,
        institution: model.value.institution,
        identifyCode: model.value.identifyCode
      }
      Entry.register(params)
        .then((res) => {
          if (res.success) {
            message.success('注册成功')
            router.push('/login')
          } else {
            message.error(res.result)
          }
        })
        .catch((err) => {
          message.error('出现错误', err)
          console.log('error:', err)
        })
    } else {
      // console.log(errors)
      message.error('请检查参数')
    }
  })
}

//表单label的样式
const labelStyle = {
  fontSize: '.975rem',
  fontWeight: '400',
  color: '#87827c'
}

onMounted(() => {})
</script>

<style lang="scss" scoped>
#container {
  width: 100%;
  min-height: calc(100vh - 73px);
  background-color: #f4f4f4;
  margin-top: 72px;
}

#login-form {
  width: 400px;

  .big-text {
    font-family: 'Roboto', Arial, sans-serif;
    font-weight: 400;
    font-size: 1.375rem;
    line-height: 1.2;
    color: #333;
    text-align: center;
    margin-top: 3vh;
  }

  .small-text {
    font-size: 0.875rem;
    font-weight: 400;
    color: #777;
    margin-bottom: 5px;
    line-height: 1.5;
    text-align: center;
    margin: 1vh 0 2vh;
  }

  // .half-size-input {
  //   .n-input {
  //     max-width: 45%;
  //   }
  // }
}

.email-modal {
  .email-text {
    font-weight: 500;
    color: #ffa157;
  }

  .n-input {
    max-width: 75%;
  }
}
</style>
